package test

import (
	"github.com/prometheus/client_golang/prometheus"
	"github.com/shirou/gopsutil/disk"
	"github.com/shirou/gopsutil/mem"
)

//var (
//	Version       = "1.0.0.dev"
//	listenAddress = flag.String("web.listen-address", ":9601", "Address to listen on for web interface and telemetry.")
//	metricPath    = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics.")
//	landingPage   = []byte("<html><head><title>Example Exporter" + Version + "</title></head><body><h1>Example Exporter" + Version + "</h1><p><ahref='" + *metricPath + "'>Metrics</a></p></body></html>")
//)

type Exporter struct {
	error        prometheus.Gauge
	scrapeErrors *prometheus.CounterVec
}

func NewExporter() *Exporter {
	return &Exporter{}
}

func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
	metricCh := make(chan prometheus.Metric)
	doneCh := make(chan struct{})
	go func() {
		for m := range metricCh {
			ch <- m.Desc()
		}
		close(doneCh)
	}()
	e.Collect(metricCh)
	close(metricCh)
	<-doneCh
}

//collect 函数，采集数据的⼊⼝
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
	var err error
	// 每个指标值的采集逻辑，在对应的采集函数中
	if err = ScrapeMem(ch); err != nil {
		e.scrapeErrors.WithLabelValues("mem").Inc()
	}
	if err = ScrapeDisk(ch); err != nil {
		e.scrapeErrors.WithLabelValues("disk").Inc()
	}
}

func ScrapeMem(ch chan<- prometheus.Metric) error {
	// 指标获取逻辑，此处不做具体操作，仅仅赋值进⾏示例
	mem_info, _ := mem.VirtualMemory()
	// ⽣成采集的指标名
	metric_name := prometheus.BuildFQName("sys", "", "mem_usage")
	// ⽣成 NewDesc 类型的数据格式，该指标⽆维度，[] string {} 为空
	new_desc := prometheus.NewDesc(metric_name, "Gauge metric with mem_usage", []string{}, nil)
	// ⽣成具体的采集信息并写⼊ ch 通道
	metric_mes := prometheus.MustNewConstMetric(new_desc,
		prometheus.GaugeValue, mem_info.UsedPercent)
	ch <- metric_mes
	return nil
}

func ScrapeDisk(ch chan<- prometheus.Metric) error {
	fs, _ := disk.Partitions(false)
	for _, val := range fs {
		d, _ := disk.Usage(val.Mountpoint)
		metric_name := prometheus.BuildFQName("sys", "", "disk_size")
		new_desc := prometheus.NewDesc(metric_name, "Gauge metric with disk_usage", []string{"mountpoint"}, nil)
		metric_mes := prometheus.MustNewConstMetric(new_desc,
			prometheus.GaugeValue, float64(d.UsedPercent), val.Mountpoint)
		ch <- metric_mes
	}
	return nil
}

//func main() {
//	// 解析定义的监听端⼝等信息
//	flag.Parse()
//	// ⽣成⼀个 Exporter 类型的对象，该 exporters 需具有 collect 和 Describe ⽅法
//	exporters := NewExporter()
//	// 将 exporters 注册⼊ prometheus，prometheus 将定期从 exporters 拉取数据
//	prometheus.MustRegister(exporters)
//	// 接收 http 请求时，触发 collect 函数，采集数据
//	http.Handle(*metricPath, promhttp.Handler())
//	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
//		w.Write(landingPage)
//	})
//	log.Fatal(http.ListenAndServe(*listenAddress, nil))
//}
